﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RedSand.Web.Mvc;
using RedSand.Site.Models;

namespace RedSand.Site.Controllers
{
    public class ProductController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Search(int? page, string keyword, int? CategoryID, int? ProviderID, string title, bool? notLayout)
        {
            notLayout = notLayout ?? false;
            ViewBag.Title = title ?? "Sản phẩm";
            ViewBag.Title = string.IsNullOrWhiteSpace(keyword) ? ViewBag.Title : "Kết quả tìm kiếm với từ khóa \"" + keyword + "\"";
            int total = 0;
            ViewBag.PageSize = 9;
            List<ProductInfo> list = RsDataManager.GetList<ProductInfo>("ProductSearch", new { CategoryID = CategoryID, ProviderID = ProviderID, KeyWord = keyword, Status = 1 }, page ?? 1, ViewBag.PageSize, ref total);
            ViewBag.TotalRecord = total;
            ViewBag.RouteValues = new { CategoryID = CategoryID, ProviderID = ProviderID, KeyWord = keyword};
            if (notLayout.Value)
            {
                return PartialView("ListProduct", list);
            }
            else
            {
                return View("ListProduct", list);
            }
        }

        public ActionResult Manager()
        {
            ManagerModel model = new ManagerModel { Title = Translate("ProductManager", "Product"), AttachTinyMce = true };
            return View(model);
        }

        [AjaxOrChildAction]
        public ActionResult List(int? page, ProductSearchModel sModel)
        {
            int total = 0;
            ViewBag.PageSize = 10;
            List<ProductInfo> list = RedSand.Web.Mvc.RsDataManager.GetList<ProductInfo>("ProductSearch", sModel, page ?? 1, ViewBag.PageSize, ref total);
            ViewBag.TotalRecord = total;
            ViewBag.RouteValues = sModel;
            return PartialView(list);
        }

        [AjaxOrChildAction]
        public ActionResult TopNew()
        {
            ViewBag.BoxTitle = "Sản phẩm mới";
            List<ProductInfo> list = RedSand.Web.Mvc.RsDataManager.GetList<ProductInfo>("ProductGetTopNew", new { TotalRecord = 6 });
            return PartialView("TopProduct", list);
        }

        [AjaxOrChildAction]
        public ActionResult TopHot()
        {
            ViewBag.BoxTitle = "Sản phẩm điển hình";
            List<ProductInfo> list = RedSand.Web.Mvc.RsDataManager.GetList<ProductInfo>("ProductGetTopHot", new { TotalRecord = 6 });
            return PartialView("TopProduct", list);
        }

        [AjaxOrChildAction, HttpGet]
        public ActionResult Create()
        {
            return PartialView("CreateN1");
        }

        [AjaxOrChildAction, HttpPost]
        public ActionResult Create(ProductInfo info, string NewImage)
        {
            if (string.IsNullOrWhiteSpace(NewImage))
            {
                return AjaxMessage(Message.ImageUrlEmpty);
            }
            if (ModelState.IsValid)
            {
                info.Image = SaveImage(null);
                info.Views = 0;
                if (RsDataManager.Save("ProductSave", info))
                {
                    info.ProductID = RsDataManager.GetLastID("Product");
                    ViewBag.IsNew = true;
                    return PartialView("CreateN2", info);
                }
                else
                {
                    return AjaxMessage(Message.CreateError);
                }
            }
            return AjaxModelError();
        }
                        
        [AjaxOrChildAction, HttpGet]
        public ActionResult Edit(int id)
        {
            return PartialView(RsDataManager.GetInfo<ProductInfo>("ProductGetInfo", "ProductID", id));
        }
        
        [AjaxOrChildAction, HttpPost]
        public ActionResult Edit(ProductInfo info)
        {
            if (ModelState.IsValid)
            {
                info.Image = SaveImage(info.Image);

                if (RsDataManager.Save("ProductSave", info))
                {
                    AddMessage(Message.UpdateSuccess);
                    return RedirectToAction("List");
                }
                else
                {
                    return AjaxMessage(Message.UpdateError);
                }
            }
            return AjaxModelError();
        }

        [AjaxOrChildAction]
        public ActionResult Tab(int id)
        {
            return PartialView(RsDataManager.GetList<ProductTabInfo>("ProductTabGetList", new { ProductID = id }));
        }

        [AjaxOrChildAction, HttpGet]
        public ActionResult CreateTab(int id)
        {
            return PartialView(new ProductTabInfo { ProductID = id });
        }

        [AjaxOrChildAction, HttpPost]
        public ActionResult CreateTab(ProductTabInfo info)
        {
            if (ModelState.IsValid)
            {
                info.Content = HtmlDecode(info.Content);
                RsDataManager.Save("ProductTabSave", info);
                return RedirectToAction("Tab", new { id = info.ProductID });
            }
            return AjaxModelError();
        }

        [AjaxOrChildAction, HttpGet]
        public ActionResult EditTab(int id)
        {
            return PartialView(RsDataManager.GetInfo<ProductTabInfo>("ProductTabGetInfo", "TabID", id));
        }

        [AjaxOrChildAction, HttpPost]
        public ActionResult EditTab(ProductTabInfo info)
        {
            if (ModelState.IsValid)
            {
                info.Content = HtmlDecode(info.Content);
                RsDataManager.Save("ProductTabSave", info);
                return RedirectToAction("Tab", new { id = info.ProductID });
            }
            return AjaxModelError();
        }

        [AjaxOrChildAction, HttpGet]
        public ActionResult DeleteTab(int id, int pid)
        {
            if (RsDataManager.Delete("ProductTabDelete", "TabID", id))
            {
                return RedirectToAction("Tab", new { id = pid });
            }
            return AjaxMessage(Message.DeleteError);
        }

        /*
        [HttpPost]
        public ActionResult AddImage(int pid)
        {
            try
            {
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase fileupload = Request.Files[0];
                    string ext = Path.GetExtension(fileupload.FileName).ToLower();
                    string filefilter = ".jpg|.png|.bmp|.jpeg|.gif";
                    if (!filefilter.Contains(ext))
                    {
                        return AjaxMessage(Message.FileFormatWrong);
                    }
                    else
                    {
                        string filePath = SaveFile(fileupload, "/Content/Upload/Product");
                        if (RsDataManager.ExecuteGetReturn("ProductAddImage", new { Image = filePath, ProductId = pid }) > 0)
                        {
                            return RedirectToAction("ListImage", new { pid = pid });
                        }
                        else
                        {
                            DeleteFile(filePath);
                            //return AjaxMessage("Lỗi thực thi dữ liệu");
                        }
                    }
                }
                return AjaxMessage(Message.FileUrlEmpty);
            }
            catch (Exception ex)
            {
                return AjaxMessage(ex.Message);
            }
        }

        [AjaxOrChildAction]
        public ActionResult RemoveImage(string Image, int pid)
        {
            if (RsDataManager.ExecuteGetReturn("ProductRemoveImage", new { Image = Image, ProductID = pid }) > 0)
            {
                DeleteFile(Image);
                return RedirectToAction("ListImage", new { pid = pid });
            }
            return AjaxMessage("Gỡ bỏ hình ảnh bị lỗi");
        }

        public ActionResult ListImage(int pid)
        {
            var images = RsDataManager.ExecuteScalar<string>("ProductGetImageList", new { ProductID = pid });
            if (string.IsNullOrWhiteSpace(images)) return PartialView("OtherImage");
            ViewBag.ProductID = pid;
            ViewBag.OtherImages = images;
            return PartialView("OtherImage", images.TrimEnd(';').Split(new[] { ';' }));
        }
        */
        [AjaxOrChildAction]
        public ActionResult Delete(int id, string image)
        {
            var images = RsDataManager.ExecuteScalar<string>("ProductGetImageList", new { ProductID = id });
            if (RsDataManager.Delete("ProductDelete", "ProductID", id))
            {
                DeleteFile(image);
                if (!string.IsNullOrWhiteSpace(images))
                {
                    var array = images.TrimEnd(';').Split(new[] { ';' });
                    foreach (var item in array)
                    {
                        DeleteFile(item);
                    }
                }
                AddMessage(Message.DeleteSuccess);
                return RedirectToAction("List");
            }
            else
            {
                return AjaxMessage(Message.DeleteError);
            }
        }

        public ActionResult Details(int id)
        {
            RsDataManager.ExecuteNonQuery("ProductAddViews", new { ProductID = id });
            return View(RsDataManager.GetInfo<ProductInfo>("ProductGetInfo", "ProductID", id));
        }

        public ActionResult Related(int id, int categoryID)
        {
            ViewBag.Title = "Sản phẩm liên quan";
            var list = RsDataManager.GetList<ProductInfo>("ProductSearch", new { CategoryID = categoryID });
            if (list != null) list = list.Where(item => item.ProductID != id).ToList();
            return PartialView(list);
        }
    }
}
